<?php

namespace utils;

class Wechat
{
    private function getAccessToken()
    {
        $appid = config('wechat.appId');
        $appsecret = config('wechat.secret');
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $res = json_decode(file_get_contents($url),true);

        if (isset($res['errcode']) && $res['errcode']) {
            $this->redirect('getCode');
        }
        return $res["access_token"];
    }

    /**
     * 首先创建二维码ticket
     * @param string $sceneid 场景值ID
     * @param string $type   值为'temp'的时候生成临时二维码
     * @param string $expire_seconds   二维码过期时间
     * @return string 二维码ticket
     */
    private function getTicket($sceneid, $type='temp', $expire_seconds=604800){
        if($type=='temp'){
            $data = '{"expire_seconds": %s, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
            $data = sprintf($data,$expire_seconds,$sceneid);
        }else{
            $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": %s}}}';
            $data = sprintf($data,$sceneid);
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->getAccessToken();
        $content = $this->post_json_data($url, $data);
        $cont = json_decode($content);
        return $cont->ticket;
    }

    //然后凭借ticket到指定URL换取二维码
    public function getQRCode($sceneid, $type='temp', $expire_seconds=604800){
        $ticket = $this->getTicket($sceneid, $type, $expire_seconds);
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($ticket);
        return $url;
    }

    private function post_json_data($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        return $return_content;
    }
}